package com.openNetty.server.timertask;
import com.openNetty.common.bean.*;
import com.openNetty.common.system.LoggerUtil;
import com.openNetty.server.main.Global;
import com.openNetty.server.proxy.BackSqlFileProxy;
import com.openNetty.server.timertask.exector.DownFileExector;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.StatefulJob;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import static com.openNetty.common.bean.Command.RELOADTASK;
import static com.openNetty.common.system.FileUtils.deleteFile;

/**
 * @author zhenggm
 * @create 2017-12-07 下午 1:12
 **/
public class DownSqlDataTask implements StatefulJob {
    private static LoggerUtil logger = LoggerUtil.getLogger(DownSqlDataTask.class);
    BackSqlFileProxy backSqlFileProxy = new BackSqlFileProxy();

    private List<String> successFile = new ArrayList<>();

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        logger.info("下载文件任务开始");
        DownFileExector backSqlDataExector = new DownFileExector();
        ComResponse result = backSqlDataExector.task();

        if (checkDownloadTask(result)) {
            successFile.forEach(filename -> Global.breakFile.remove(filename));
        }
        logger.debug("任务结束" + context.getJobDetail().getFullName());
    }

    /**
     * 检查下载任务是否完成，未完成进行相应处理
     * @param response
     * @return
     */
    public boolean checkDownloadTask(ComResponse response) {
        boolean result = response.isSuccess();
        // 如果任务执行失败
        try {
            if (!result) {
                if (Global.breakFile.size() == 0) {
                    logger.debug("未找到断点记录文件，" + Global.properties.getProperty("back.breaktime") + "ms后重新执行下载程序。");
                    Thread.sleep(Long.parseLong(Global.properties.getProperty("back.breaktime")));
                    if (response.getFilePath() != null) {
                        File file = new File(response.getFilePath());
                        if (deleteFile(file)) {
                            logger.debug("清理旧数据成功");
                        } else {
                            logger.error("清理旧数据失败");
                        }
                    }
                    DownFileExector backUpExector = new DownFileExector();
                    ComResponse comResponse = backUpExector.task();
                    if (!comResponse.isSuccess()) {
                        checkDownloadTask(comResponse);
                    }
                } else {
                    logger.info("断点记录成功，" + Global.properties.getProperty("back.breaktime") + "ms后尝试重新下载。");
                    Thread.sleep(Long.parseLong(Global.properties.getProperty("back.breaktime")));
                    logger.info("开始尝试重连。。。");
                    BackNode backNode = new BackNode();
                    backNode.setRoot(Global.properties.getProperty("back.root"));
                    backNode.setAddress(Global.properties.getProperty("back.address"));
                    backNode.setPort(Global.properties.getProperty("back.port"));

                    // 遍历breakMAP
                    Iterator<Map.Entry<String, HttpAck>> it = Global.breakFile.entrySet().iterator();
                    while (it.hasNext()) {
                        Map.Entry<String, HttpAck> entry = it.next();
                        ComRequest comRequest = new ComRequest();
                        comRequest.setBackNode(backNode);
                        comRequest.setMethod(HttpInfo.GET);
                        comRequest.setMessage(Command.GET_BREAK_BACKFILE);// 状态为重连
                        comRequest.setHttpAck(entry.getValue());
                        comRequest.getHttpAck().setFileName(entry.getKey());
                        logger.debug("发送断点位置==》" + entry.getValue().getCount() + "/" + entry.getValue().getPostition() + entry.getKey());
                        ComResponse comResponse = backSqlFileProxy.getSqlBackFile(comRequest);
                        if (!comResponse.isSuccess()) {
                            if (RELOADTASK.equals(comResponse.getResult())) {
                                File file = new File(comResponse.getFilePath());
                                if (deleteFile(file)) {
                                    logger.debug("清理旧数据成功");
                                } else {
                                    logger.error("清理旧数据失败");
                                }
                                it.remove();// 断点缓存中清除对应的KEY
                            }
                            // 不是校验错误不清除
                            checkDownloadTask(comResponse);
                        } else {
                            successFile.add(entry.getKey());
                        }
                    }
                }
            }
        } catch (InterruptedException e) {
            logger.error(e);
        }
        return result;
    }
}
